package com.ems.servlet;

import com.ems.dao.UserDAO;
import com.ems.model.User;
import com.ems.util.PasswordUtil;
import java.io.IOException;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String userId = request.getParameter("userId");
        String password = request.getParameter("password");
        String role = request.getParameter("role");

        try {
            UserDAO userDAO = new UserDAO();
            User user = userDAO.getUserById(userId);

            if (user != null && user.getRole().equals(role) &&
                    PasswordUtil.checkPassword(password, user.getPassword())) {
                HttpSession session = request.getSession();
                session.setAttribute("user", user);

                if (role.equals("admin")) {
//                    response.sendRedirect("home.jsp");
                    RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/admin/home.jsp");
                    dispatcher.forward(request, response);
                } else {
                  //  response.sendRedirect("profile.jsp");
                    RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/admin/profile.jsp");
                    dispatcher.forward(request, response);
                }
            } else {
                request.setAttribute("error", "用户名或密码错误");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "登录失败，请稍后再试");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.sendRedirect("login.jsp");
    }
}